#include "HAL.h"

uint8_t menu_index = 0;

void HAL_KeyInit( void )
{
    KEY_UP_DIR; //IO输入
    KEY_UP_PU; //IO上拉
    KEY_DOWN_DIR; //IO输入
    KEY_DOWN_PU; //IO上拉
    KEY_ENTER_DIR; //IO输入
    KEY_ENTER_PU; //IO上拉
}

uint8 HAL_KeyPoll(void)
{
    static uint8 Prev_ScanKeys = 0;  //前一次按键的扫描值
    static uint8 Prev_ValidKeys = 0; //前一次按键的有效值(消抖后)
    uint8 keys = 0;                  //本次扫描值
    uint8 value = 0;                 //返回值

    if (HAL_PUSH_BUTTON_UP())
    {
        keys |= HAL_KEY_SW_UP;
    }
    if(HAL_PUSH_BUTTON_DOWN())
    {
        keys |= HAL_KEY_SW_DOWN;
    }
    if(HAL_PUSH_BUTTON_ENTER())
    {
        keys |= HAL_KEY_SW_ENTER;
    }
    if (Prev_ScanKeys == keys) //两次键值一样,键值有效
    {
        if ((keys & HAL_KEY_SW_UP) && !(Prev_ValidKeys & HAL_KEY_SW_UP)) //key up首次按下
        {
            value = HAL_KEY_SW_UP;
        }
        if ((keys & HAL_KEY_SW_DOWN) && !(Prev_ValidKeys & HAL_KEY_SW_DOWN)) //key down首次按下
        {
            value = HAL_KEY_SW_DOWN;
        }
        if ((keys & HAL_KEY_SW_ENTER) && !(Prev_ValidKeys & HAL_KEY_SW_ENTER)) //key enter首次按下
        {
            value = HAL_KEY_SW_ENTER;
        }
        Prev_ValidKeys = keys; //保存有效值
    }
    Prev_ScanKeys = keys; //保存键值

    return value;
}
